/**
 * 
 */
package com.utils;

import java.security.MessageDigest;
import java.util.zip.CRC32;

import sun.misc.BASE64Encoder;

/**
 */
public class MD5UtilSecurity
{
  private static char hexDigits[] =
  { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
      'f' };

  /**
   * description
   * 
   * @param str
   * @return
   * @throws Exception
   */
  public static String crcDigest(String str) throws Exception
  {
    byte[] buf = str.getBytes();
    java.util.zip.Checksum checksumEngine = new CRC32();
    checksumEngine.update(buf, 0, buf.length);
    return Long.toHexString(checksumEngine.getValue());
  }

  /**
   * description
   * 
   * @param string
   * @return
   * @throws Exception
   */
  public static String md5Digest(String s) throws Exception
  {
    try
    {
      byte[] strTemp = s.getBytes("UTF-8");
      MessageDigest mdTemp = MessageDigest.getInstance("MD5");
      mdTemp.update(strTemp);
      byte[] md = mdTemp.digest();
      int j = md.length;
      char str[] = new char[j * 2];
      int k = 0;
      for (int i = 0; i < j; i++)
      {
        byte byte0 = md[i];
        str[k++] = hexDigits[byte0 >>> 4 & 0xf];
        str[k++] = hexDigits[byte0 & 0xf];
      }
      return new String(str);
    }
    catch (Exception e)
    {
      return null;
    }
  }

  /**
   * description
   * 
   * @param buf
   * @return
   * @throws Exception
   */
  public static String md5Digest(byte[] buf) throws Exception
  {
    BASE64Encoder base64en = new BASE64Encoder();
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    return base64en.encode(md5.digest(buf));
  }
}
